/**
 * 分析结果管理器
 * 负责管理分析结果查询、展示和相关功能
 */
class AnalysisResultsManager {
    constructor() {
        this.currentTab = 'regional';
        this.currentPage = 1;
        this.pageSize = 20;
        this.filters = {};
        this.cache = new Map();
        this.isLoading = false;
        
        // 分析类型配置
        this.analysisTypes = {
            'regional': {
                name: '区域分析',
                icon: 'fas fa-map-marker-alt',
                apiType: 'regional',
                columns: [
                    { key: 'petition_record_id', label: '信访编号', width: '10%', truncate: false },
                    { key: 'tsr', label: '投诉人', width: '8%', truncate: false },
                    { key: 'xfnr', label: '信访内容', width: '45%', truncate: true },
                    { key: 'dzxx_xzq', label: '区域', width: '10%', truncate: false },
                    { key: 'dzxx_jd', label: '街道', width: '8%', truncate: false },
                    { key: 'confidence', label: '置信度', width: '8%', truncate: false },
                    { key: 'created_at', label: '分析时间', width: '13%', truncate: false },
                    { key: 'actions', label: '操作', width: '8%', truncate: false }
                ]
            },
            'complaint-type': {
                name: '投诉类型分析',
                icon: 'fas fa-tags',
                apiType: 'complaint-type',
                columns: [
                    { key: 'petition_record_id', label: '信访编号', width: '10%', truncate: false },
                    { key: 'xfnr', label: '信访内容', width: '25%', truncate: true },
                    { key: 'full_complaint_type', label: '投诉类型', width: '18%', truncate: false },
                    { key: 'level2_confidence', label: '二级置信度', width: '12%', truncate: false },
                    { key: 'level3_confidence', label: '三级置信度', width: '12%', truncate: false },
                    { key: 'created_at', label: '分析时间', width: '13%', truncate: false },
                    { key: 'actions', label: '操作', width: '10%', truncate: false }
                ]
            },
            'sentiment': {
                name: '情感分析',
                icon: 'fas fa-heart',
                apiType: 'sentiment',
                columns: [
                    { key: 'petition_record_id', label: '信访编号', width: '10%', truncate: false },
                    { key: 'xfnr', label: '信访内容', width: '25%', truncate: true },
                    { key: 'sentiment_level', label: '情感类型', width: '10%', truncate: false },
                    { key: 'qgfx_zy', label: '摘要', width: '20%', truncate: true },
                    { key: 'keywords_list', label: '关键词', width: '12%', truncate: false },
                    { key: 'created_at', label: '分析时间', width: '13%', truncate: false },
                    { key: 'actions', label: '操作', width: '10%', truncate: false }
                ]
            },
            'compliance': {
                name: '规范性分析',
                icon: 'fas fa-check-circle',
                apiType: 'compliance',
                columns: [
                    { key: 'petition_record_id', label: '信访编号', width: '10%', truncate: false },
                    { key: 'xfnr', label: '信访内容', width: '25%', truncate: true },
                    { key: 'gffx_dfnr', label: '答复内容', width: '20%', truncate: true },
                    { key: 'compliance_status', label: '合规状态', width: '10%', truncate: false },
                    { key: 'gffx_pdly', label: '判断理由', width: '12%', truncate: true },
                    { key: 'created_at', label: '分析时间', width: '13%', truncate: false },
                    { key: 'actions', label: '操作', width: '10%', truncate: false }
                ]
            },
            'duplicate': {
                name: '重复分析',
                icon: 'fas fa-copy',
                apiType: 'duplicate',
                columns: [
                    { key: 'cfbh', label: '重复组编号', width: '12%', truncate: false },
                    { key: 'xfxh', label: '信访编号', width: '12%', truncate: false },
                    { key: 'petition_record', label: '信访信息', width: '30%', truncate: true },
                    { key: 'task_id', label: '任务ID', width: '10%', truncate: false },
                    { key: 'created_at', label: '分析时间', width: '16%', truncate: false },
                    { key: 'actions', label: '操作', width: '10%', truncate: false }
                ]
            }
        };
        
        this.init();
    }
    
    /**
     * 初始化管理器
     */
    init() {
        console.log('分析结果管理器初始化');
        this.bindEvents();
        this.loadInitialData();
    }
    
    /**
     * 绑定事件
     */
    bindEvents() {
        // Tab切换事件
        document.querySelectorAll('.analysis-tab').forEach(tab => {
            tab.addEventListener('click', (e) => {
                const tabType = e.target.getAttribute('data-tab');
                this.switchTab(tabType);
            });
        });
        
        // 监听Enter键搜索
        document.getElementById('searchInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.applyFilters();
            }
        });
        
        // 模态框外部点击关闭
        document.getElementById('resultDetailModal').addEventListener('click', (e) => {
            if (e.target.id === 'resultDetailModal') {
                this.closeDetailModal();
            }
        });
    }
    
    /**
     * 加载初始数据
     */
    async loadInitialData() {
        try {
            await this.loadTaskOptions();
            await this.loadRegionOptions();
            await this.loadTypeOptions();
            await this.loadDashboardStats();
            await this.loadResults();
        } catch (error) {
            console.error('加载初始数据失败:', error);
            this.showError('加载数据失败，请刷新页面重试');
        }
    }
    
    /**
     * 切换Tab
     */
    async switchTab(tabType) {
        if (this.currentTab === tabType) return;
        
        // 更新Tab状态
        document.querySelectorAll('.analysis-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelector(`[data-tab="${tabType}"]`).classList.add('active');
        
        this.currentTab = tabType;
        this.currentPage = 1;
        this.filters = {};
        
        // 重新加载数据
        await this.loadInitialData();
    }
    
    /**
     * 加载任务选项
     */
    async loadTaskOptions() {
        try {
            const response = await fetch(`/api/analysis-results-new/options/?analysis_type=${this.currentTab}&option_type=tasks`);
            const result = await response.json();
            
            if (result.code === 200) {
                const select = document.getElementById('taskFilter');
                select.innerHTML = '<option value="">全部任务</option>';
                
                result.data.forEach(task => {
                    const option = document.createElement('option');
                    option.value = task.value;
                    option.textContent = task.label;
                    select.appendChild(option);
                });
            }
        } catch (error) {
            console.error('加载任务选项失败:', error);
        }
    }
    
    /**
     * 加载区域选项
     */
    async loadRegionOptions() {
        try {
            const response = await fetch(`/api/analysis-results-new/options/?analysis_type=${this.currentTab}&option_type=regions`);
            const result = await response.json();
            
            if (result.code === 200) {
                const districtSelect = document.getElementById('districtFilter');
                const streetSelect = document.getElementById('streetFilter');
                
                districtSelect.innerHTML = '<option value="">全部区县</option>';
                streetSelect.innerHTML = '<option value="">全部街道</option>';
                
                result.data.districts.forEach(district => {
                    const option = document.createElement('option');
                    option.value = district;
                    option.textContent = district;
                    districtSelect.appendChild(option);
                });
                
                // 保存街道数据用于级联选择
                this.streetData = result.data.streets || {};
            }
        } catch (error) {
            console.error('加载区域选项失败:', error);
        }
    }
    
    /**
     * 加载街道选项（级联）
     */
    async loadStreetOptions() {
        const districtSelect = document.getElementById('districtFilter');
        const streetSelect = document.getElementById('streetFilter');
        const selectedDistrict = districtSelect.value;
        
        streetSelect.innerHTML = '<option value="">全部街道</option>';
        
        if (selectedDistrict && this.streetData[selectedDistrict]) {
            this.streetData[selectedDistrict].forEach(street => {
                const option = document.createElement('option');
                option.value = street;
                option.textContent = street;
                streetSelect.appendChild(option);
            });
        }
        
        this.applyFilters();
    }
    
    /**
     * 加载类型选项
     */
    async loadTypeOptions() {
        try {
            const response = await fetch(`/api/analysis-results-new/options/?analysis_type=${this.currentTab}&option_type=types`);
            const result = await response.json();
            
            if (result.code === 200) {
                const typeSelect = document.getElementById('typeFilter');
                typeSelect.innerHTML = '<option value="">全部类型</option>';
                
                if (this.currentTab === 'complaint-type') {
                    // 投诉类型特殊处理
                    result.data.level1.forEach(type => {
                        const option = document.createElement('option');
                        option.value = type;
                        option.textContent = type;
                        typeSelect.appendChild(option);
                    });
                } else if (this.currentTab === 'sentiment') {
                    // 情感类型
                    result.data.forEach(type => {
                        const option = document.createElement('option');
                        option.value = type;
                        option.textContent = type;
                        typeSelect.appendChild(option);
                    });
                } else if (this.currentTab === 'compliance') {
                    // 合规状态
                    result.data.forEach(type => {
                        const option = document.createElement('option');
                        option.value = type.value;
                        option.textContent = type.label;
                        typeSelect.appendChild(option);
                    });
                }
            }
        } catch (error) {
            console.error('加载类型选项失败:', error);
        }
    }
    
    /**
     * 加载仪表板统计数据
     */
    async loadDashboardStats() {
        try {
            const response = await fetch(`/api/analysis-results-new/dashboard-stats/?analysis_type=${this.currentTab}`);
            const result = await response.json();

            if (result.code === 200 && result.data && typeof result.data === 'object') {
                const stats = result.data;
                // 安全地获取统计数据，设置默认值
                const total = typeof stats.total === 'number' ? stats.total : 0;
                const today = typeof stats.today === 'number' ? stats.today : 0;
                const avgConfidence = typeof stats.avg_confidence === 'number' ? stats.avg_confidence : 0;
                const coverageRate = typeof stats.coverage_rate === 'number' ? stats.coverage_rate : 0;

                document.getElementById('totalResults').textContent = total.toLocaleString();
                document.getElementById('todayResults').textContent = today.toLocaleString();
                document.getElementById('avgConfidence').textContent = `${avgConfidence.toFixed(1)}%`;
                document.getElementById('coverageRate').textContent = `${coverageRate.toFixed(1)}%`;
            } else {
                // 设置默认值，避免显示undefined
                document.getElementById('totalResults').textContent = '0';
                document.getElementById('todayResults').textContent = '0';
                document.getElementById('avgConfidence').textContent = '0%';
                document.getElementById('coverageRate').textContent = '0%';
                console.warn('统计数据格式异常:', result);
            }
        } catch (error) {
            console.error('加载统计数据失败:', error);
            // 设置默认值，避免显示undefined
            document.getElementById('totalResults').textContent = '-';
            document.getElementById('todayResults').textContent = '-';
            document.getElementById('avgConfidence').textContent = '-';
            document.getElementById('coverageRate').textContent = '-';
        }
    }
    
    /**
     * 应用过滤器
     */
    applyFilters() {
        this.currentPage = 1;
        this.filters = this.getFilterValues();
        this.loadResults();
    }
    
    /**
     * 获取过滤器值
     */
    getFilterValues() {
        return {
            task_id: document.getElementById('taskFilter').value || null,
            district: document.getElementById('districtFilter').value || null,
            street: document.getElementById('streetFilter').value || null,
            type_filter: document.getElementById('typeFilter').value || null,
            start_date: document.getElementById('startDateFilter').value || null,
            end_date: document.getElementById('endDateFilter').value || null,
            search: document.getElementById('searchInput').value || null
        };
    }
    
    /**
     * 重置过滤器
     */
    resetFilters() {
        document.getElementById('taskFilter').value = '';
        document.getElementById('districtFilter').value = '';
        document.getElementById('streetFilter').value = '';
        document.getElementById('typeFilter').value = '';
        document.getElementById('startDateFilter').value = '';
        document.getElementById('endDateFilter').value = '';
        document.getElementById('searchInput').value = '';
        
        this.filters = {};
        this.currentPage = 1;
        this.loadResults();
    }
    
    /**
     * 加载分析结果
     */
    async loadResults() {
        if (this.isLoading) return;
        
        this.showLoading(true);
        
        try {
            // 构建查询参数
            const params = new URLSearchParams({
                analysis_type: this.currentTab,
                page: this.currentPage,
                page_size: this.pageSize
            });
            
            // 添加过滤器参数
            Object.entries(this.filters).forEach(([key, value]) => {
                if (value !== null && value !== '') {
                    params.append(key, value);
                }
            });
            
            // 检查缓存
            const cacheKey = params.toString();
            if (this.cache.has(cacheKey)) {
                const cachedData = this.cache.get(cacheKey);
                this.renderResults(cachedData);
                this.showLoading(false);
                return;
            }
            
            const response = await fetch(`/api/analysis-results-new/unified/?${params}`);
            const result = await response.json();
            
            if (result.code === 200) {
                // 缓存结果
                const data = result.data || result; // 兼容新旧格式
                this.cache.set(cacheKey, data);
                this.renderResults(data);
            } else {
                this.showError(result.message || '加载数据失败');
            }
        } catch (error) {
            console.error('加载分析结果失败:', error);
            this.showError('网络错误，请稍后重试');
        } finally {
            this.showLoading(false);
        }
    }
    
    /**
     * 渲染结果
     */
    renderResults(data) {
        const container = document.getElementById('resultsTableContainer');

        // 验证数据结构
        if (!data || typeof data !== 'object') {
            console.error('无效的响应数据:', data);
            this.showError('数据格式错误');
            this.showEmptyState();
            return;
        }

        // 处理不同的数据格式
        const validatedData = {
            items: Array.isArray(data.items) ? data.items :
                   Array.isArray(data) ? data : [],
            total: typeof data.total === 'number' ? data.total :
                   Array.isArray(data.items) ? data.items.length :
                   Array.isArray(data) ? data.length : 0,
            page: typeof data.page === 'number' ? data.page : 1,
            page_size: typeof data.page_size === 'number' ? data.page_size : 20,
            total_pages: typeof data.total_pages === 'number' ? data.total_pages :
                       Math.ceil((typeof data.total === 'number' ? data.total :
                                (Array.isArray(data.items) ? data.items.length : 0)) / 20)
        };

        if (validatedData.total === 0) {
            this.showEmptyState();
            return;
        }

        // 渲染表格头部
        this.renderTableHeader();

        // 渲染表格数据
        this.renderTableBody(validatedData.items);

        // 渲染分页
        this.renderPagination(validatedData);

        // 显示表格区域
        document.getElementById('resultsTableArea').classList.remove('hidden');
        document.getElementById('resultsPagination').classList.remove('hidden');
        document.getElementById('resultsEmptyState').classList.add('hidden');
    }
    
    /**
     * 渲染表格头部
     */
    renderTableHeader() {
        const header = document.getElementById('resultsTableHeader');
        const columns = this.analysisTypes[this.currentTab].columns;

        header.innerHTML = columns.map(col =>
            `<th class="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider whitespace-nowrap" style="width: ${col.width}">
                ${col.label}
            </th>`
        ).join('');
    }
    
    /**
     * 渲染表格数据
     */
    renderTableBody(items) {
        const tbody = document.getElementById('resultsTableBody');
        const columns = this.analysisTypes[this.currentTab].columns;

        tbody.innerHTML = items.map(item => {
            const row = columns.map(col => {
                let value = item[col.key] || '';

                // 特殊处理某些字段 - 移除JavaScript层面的截断，让CSS来处理
                // if (col.truncate && value.length > 100) {
                //     value = value.substring(0, 100) + '...';
                // }

                if (col.key === 'actions') {
                    return `<td class="px-4 py-4 whitespace-nowrap text-sm text-slate-500" style="width: ${col.width || 'auto'}">
                        <button onclick="analysisResultsManager.showDetail(${item.id})" class="text-indigo-600 hover:text-indigo-900 mr-3">
                            <i class="fas fa-eye"></i> 查看
                        </button>
                    </td>`;
                }

                if (col.key === 'confidence') {
                    value = `${Math.round(value * 100)}%`;
                }

                if (col.key === 'level2_confidence' || col.key === 'level3_confidence') {
                    value = `${Math.round(value * 100)}%`;
                }

                if (col.key === 'created_at') {
                    value = new Date(value).toLocaleString('zh-CN');
                }

                if (col.key === 'keywords_list') {
                    value = Array.isArray(value) ? value.slice(0, 3).join(', ') : '';
                }

                // 根据是否需要truncate来决定样式
                const cellClass = col.truncate
                    ? 'px-4 py-4 text-sm text-slate-900 truncate-cell'
                    : 'px-4 py-4 text-sm text-slate-900 no-truncate';

                return `<td class="${cellClass}" style="width: ${col.width}" title="${col.truncate ? (item[col.key] || '') : ''}">${value}</td>`;
            }).join('');

            return `<tr class="hover:bg-slate-50">${row}</tr>`;
        }).join('');
    }
    
    /**
     * 渲染分页
     */
    renderPagination(data) {
        const container = document.getElementById('paginationContainer');
        const totalPages = data.total_pages;
        const currentPage = data.page;
        
        // 更新分页信息
        document.getElementById('pageStart').textContent = ((currentPage - 1) * this.pageSize + 1);
        document.getElementById('pageEnd').textContent = Math.min(currentPage * this.pageSize, data.total);
        document.getElementById('totalItems').textContent = data.total;
        
        // 生成分页按钮
        let paginationHTML = '';
        
        // 上一页
        paginationHTML += `
            <button onclick="analysisResultsManager.goToPage(${currentPage - 1})" 
                    class="page-btn px-3 py-1 rounded-lg ${currentPage === 1 ? 'disabled' : ''}" 
                    ${currentPage === 1 ? 'disabled' : ''}>
                <i class="fas fa-chevron-left"></i>
            </button>
        `;
        
        // 页码按钮
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);
        
        if (startPage > 1) {
            paginationHTML += `<button onclick="analysisResultsManager.goToPage(1)" class="page-btn px-3 py-1 rounded-lg">1</button>`;
            if (startPage > 2) {
                paginationHTML += `<span class="px-2 text-slate-400">...</span>`;
            }
        }
        
        for (let i = startPage; i <= endPage; i++) {
            paginationHTML += `
                <button onclick="analysisResultsManager.goToPage(${i})" 
                        class="page-btn px-3 py-1 rounded-lg ${i === currentPage ? 'active' : ''}">
                    ${i}
                </button>
            `;
        }
        
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                paginationHTML += `<span class="px-2 text-slate-400">...</span>`;
            }
            paginationHTML += `<button onclick="analysisResultsManager.goToPage(${totalPages})" class="page-btn px-3 py-1 rounded-lg">${totalPages}</button>`;
        }
        
        // 下一页
        paginationHTML += `
            <button onclick="analysisResultsManager.goToPage(${currentPage + 1})" 
                    class="page-btn px-3 py-1 rounded-lg ${currentPage === totalPages ? 'disabled' : ''}" 
                    ${currentPage === totalPages ? 'disabled' : ''}>
                <i class="fas fa-chevron-right"></i>
            </button>
        `;
        
        container.innerHTML = paginationHTML;
    }
    
    /**
     * 跳转到指定页
     */
    goToPage(page) {
        if (page < 1) return;
        this.currentPage = page;
        this.loadResults();
    }
    
    /**
     * 显示详情
     */
    async showDetail(id) {
        try {
            // 这里可以根据需要实现详情加载逻辑
            console.log('显示详情:', id);
            // 显示模态框
            document.getElementById('resultDetailModal').classList.remove('hidden');
            document.getElementById('resultDetailModal').classList.add('flex');
        } catch (error) {
            console.error('显示详情失败:', error);
        }
    }
    
    /**
     * 关闭详情模态框
     */
    closeDetailModal() {
        document.getElementById('resultDetailModal').classList.add('hidden');
        document.getElementById('resultDetailModal').classList.remove('flex');
    }
    
    /**
     * 刷新结果
     */
    refreshResults() {
        this.cache.clear();
        this.loadResults();
        this.loadDashboardStats();
    }
    
    /**
     * 改变每页显示行数
     */
    changePageSize(pageSize) {
        this.pageSize = parseInt(pageSize);
        this.currentPage = 1;
        this.loadResults();
    }

    /**
     * 导出结果
     */
    exportResults() {
        // 这里可以实现导出逻辑
        console.log('导出结果');
        alert('导出功能开发中...');
    }
    
    /**
     * 显示加载状态
     */
    showLoading(show) {
        this.isLoading = show;
        const loadingState = document.getElementById('resultsLoadingState');
        const tableArea = document.getElementById('resultsTableArea');

        if (show) {
            if (loadingState) {
                loadingState.classList.remove('hidden');
                // 增强加载状态UI
                loadingState.innerHTML = `
                    <div class="flex flex-col items-center justify-center py-12">
                        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mb-4"></div>
                        <p class="text-gray-600 text-lg">正在加载数据...</p>
                        <p class="text-gray-500 text-sm mt-2">请稍候，正在从服务器获取分析结果</p>
                    </div>
                `;
            }
            if (tableArea) {
                tableArea.classList.add('hidden');
            }
        } else {
            if (loadingState) {
                loadingState.classList.add('hidden');
            }
        }
    }
    
    /**
     * 显示空状态
     */
    showEmptyState(error = null) {
        const tableArea = document.getElementById('resultsTableArea');
        const pagination = document.getElementById('resultsPagination');
        const emptyState = document.getElementById('resultsEmptyState');

        if (tableArea) tableArea.classList.add('hidden');
        if (pagination) pagination.classList.add('hidden');

        if (emptyState) {
            emptyState.classList.remove('hidden');
            // 增强空状态UI
            if (error) {
                emptyState.innerHTML = `
                    <div class="text-center py-12">
                        <i class="fas fa-exclamation-triangle text-6xl text-yellow-500 mb-4"></i>
                        <h3 class="text-xl font-semibold text-gray-700 mb-2">数据加载失败</h3>
                        <p class="text-gray-500 mb-6">${error}</p>
                        <button onclick="analysisResultsManager.refreshResults()" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                            <i class="fas fa-refresh mr-2"></i>重新加载
                        </button>
                    </div>
                `;
            } else {
                const analysisTypeName = this.analysisTypes[this.currentTab]?.name || '分析结果';
                emptyState.innerHTML = `
                    <div class="text-center py-12">
                        <i class="fas fa-search text-6xl text-gray-400 mb-4"></i>
                        <h3 class="text-xl font-semibold text-gray-700 mb-2">暂无${analysisTypeName}</h3>
                        <p class="text-gray-500 mb-6">当前条件下没有找到相关的分析结果</p>
                        <div class="space-y-3">
                            <button onclick="analysisResultsManager.resetFilters()" class="px-6 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors">
                                <i class="fas fa-filter mr-2"></i>重置筛选条件
                            </button>
                            <button onclick="analysisResultsManager.refreshResults()" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors ml-3">
                                <i class="fas fa-refresh mr-2"></i>刷新数据
                            </button>
                        </div>
                    </div>
                `;
            }
        }
    }
    
    /**
     * 显示错误信息
     */
    showError(message, type = 'error') {
        console.error(message);

        // 创建友好的错误提示组件
        const errorContainer = document.createElement('div');
        errorContainer.className = `fixed top-4 right-4 z-50 max-w-md p-4 rounded-lg shadow-lg transition-all duration-300 transform translate-x-full`;

        // 根据错误类型设置样式
        const bgColor = type === 'error' ? 'bg-red-500' : type === 'warning' ? 'bg-yellow-500' : 'bg-blue-500';
        const icon = type === 'error' ? 'fas fa-exclamation-circle' :
                    type === 'warning' ? 'fas fa-exclamation-triangle' : 'fas fa-info-circle';

        errorContainer.innerHTML = `
            <div class="flex items-center ${bgColor} text-white p-4 rounded-lg">
                <i class="${icon} mr-3"></i>
                <div class="flex-1">
                    <p class="font-medium">${message}</p>
                </div>
                <button onclick="this.parentElement.parentElement.remove()" class="ml-4 text-white hover:text-gray-200">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;

        document.body.appendChild(errorContainer);

        // 显示动画
        setTimeout(() => {
            errorContainer.classList.remove('translate-x-full');
        }, 100);

        // 自动隐藏
        setTimeout(() => {
            errorContainer.classList.add('translate-x-full');
            setTimeout(() => {
                if (errorContainer.parentElement) {
                    errorContainer.remove();
                }
            }, 300);
        }, 5000);
    }

    /**
     * 显示成功信息
     */
    showSuccess(message) {
        this.showError(message, 'success');
    }

    /**
     * 显示警告信息
     */
    showWarning(message) {
        this.showError(message, 'warning');
    }
}

// 全局实例，供HTML调用
let analysisResultsManager;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    analysisResultsManager = new AnalysisResultsManager();
});